<template>
  <div class="page-container">
    <!-- Logo部分 -->
    <div class="logo-container">
      <a href="/" class="nav-logo-link" aria-label="Amazon">
        <img src="@/assets/images/Amazon_logo.svg.webp" alt="Amazon" class="amazon-logo" />
      </a>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="login-container">
        <!-- 注册框 -->
        <div class="a-box">
          <div class="a-box-inner">
            <h1 class="a-spacing-small">{{ $t('创建账户') }}</h1>

            <form @submit.prevent="handleRegister">
              <!-- 姓名输入框 -->
<!--              <div class="a-form-field">-->
<!--                <label class="a-form-label">您的姓名</label>-->
<!--                <input-->
<!--                  v-model="form.name"-->
<!--                  type="text"-->
<!--                  ref="nameInput"-->
<!--                  class="a-input-text"-->
<!--                  :class="{ 'a-form-error': formErrors.name }"-->
<!--                />-->
<!--              </div>-->

              <!-- 邮箱输入框 -->
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('电子邮件') }}</label>
                <input
                  v-model="form.username"
                  type="username"
                  class="a-input-text"
                  :class="{ 'a-form-error': formErrors.username }"
                />
              </div>
              <!-- 验证码 -->
              <div class="a-form-field" v-if="GETCODE_SETTING.emailCodeRegisterFlag">
                <label class="a-form-label">{{ $t('验证码') }}</label>
                <div>
                  <div>
                  <input
                  v-model="form.emailCode"
                  ref="email"
                  class="a-input-text"
                  :placeholder="$t('请输入验证码')"

                />
                <!-- @blur="validateEmailCod" -->
                </div>
                <div>
                  <el-button link :disabled="countdown > 0" @click="handleResend" style="color: #f0c14b;">
                      {{ countdown > 0 ? `${$t('重新发送')} (${countdown}s)` : $t('发送验证码') }}
                    </el-button>
                </div>
                </div>
              </div>
              <div class="a-form-field" v-if="GETCODE_SETTING.captchaRegisterH5">
                <label class="a-form-label">{{ $t('验证码') }}</label>
                <div style=" display: flex;align-items: center;justify-content: space-between;">
                  <div style="width: 70%;">
                  <input
                  v-model="form.captcha"
                  ref="captcha"
                  class="a-input-text"

                  :placeholder="$t('请输入验证码')"

                />
                  <!--          @blur="validateEmailCod"  -->

                </div>
                <img @click="getcaptchaImage" style="width: 30%;height: 30px;" :src="codeUrl" alt="" srcset="">
                </div>
              </div>
              <!-- 密码输入框 -->
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('密码') }}</label>
                <input
                  v-model="form.password"
                  type="password"
                  :placeholder="$t('至少 6 个字符')"
                  class="a-input-text"
                  :class="{ 'a-form-error': formErrors.password }"
                />
                <div class="a-form-alert">
                  <i class="fas fa-info-circle"></i>
                  <span>{{ $t('密码必须至少包含 6 个字符。') }}</span>
                </div>
              </div>

              <!-- 确认密码输入框 -->
              <div class="a-form-field">
                <label class="a-form-label">{{ $t('再次输入密码') }}</label>
                <input
                  v-model="form.confirmPassword"
                  type="password"
                  class="a-input-text"
                  :placeholder="$t('再次输入密码')"
                  :class="{ 'a-form-error': formErrors.confirmPassword }"
                />
              </div>
              <!-- 邀请码输入框 -->
              <div class="a-form-field" v-if="GETCODE_SETTING.inviteCode">
                <label class="a-form-label">{{ $t('邀请码') }}</label>
                <input
                  v-model="form.inviteCode"
                  type="text"
                  :placeholder="$t('邀请码')"
                  class="a-input-text"
                />
              </div>

              <!-- 继续按钮 -->
              <button
                type="submit"
                class="a-button-primary"
                :disabled="isLoading"
              >
                {{ isLoading ?  $t('注册中...')  : $t('注册')  }}
              </button>

              <!-- 使用条款 -->
              <div class="a-spacing-top-small a-size-mini">
                <span>{{ $t('创建账户即表示您同意的') }}</span>
                <router-link to="/protocol?key=userContract" class="a-link-normal">{{ $t('用户协议') }}</router-link>
                <span>{{ $t('') }}和</span>
                <router-link to="/protocol?key=secrecyContract" class="a-link-normal">{{ $t('隐私协议') }}</router-link>。
              </div>

              <!-- 分隔线 -->
              <div class="a-divider-inner"></div>

              <!-- 已有账户 -->
              <div class="sign-in-link">
                <span class="a-size-mini">{{ $t('已有账户？') }}</span>
                <router-link to="/login" class="a-link-normal a-size-mini">{{ $t('登录') }}</router-link>
              </div>

              <!-- 工作采购 -->
              <div class="business-section">
                <span class="a-size-mini">{{ $t('采购优惠卷？') }}</span>
                <a class="a-link-disabled a-size-mini">{{ $t('请先创建账户') }}</a>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ApiRegister } from '@/api/login'
import Footer from '../components/Footer.vue'
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import { ApiSendEmail } from '@/api/public'
import { ApiConfig ,captchaImage} from "@/api/common";
const router = useRouter()
const route = useRoute()
const nameInput = ref<HTMLInputElement | null>(null)
const isLoading = ref(false)
const formErrors = reactive({
  name: false,
  username: false,
  password: false,
  confirmPassword: false
})

const form = reactive({
  name: '',
  username: '',
  emailCode:'',
  captcha:"",
  uuid:'',
  password: '',
  confirmPassword: '',
  inviteCode: route.query.inviteCode || ''
})
const imgCode = ref({});
const codeUrl = ref('');
//获取图形验证码
const getcaptchaImage = async () => {
  let res = await captchaImage();
  console.log('sdfsf');
  imgCode.value = res.data;
  codeUrl.value = 'data:image/gif;base64,'+res.data.img
  form.uuid = res.data.uuid;

}
const GETCODE_SETTING = ref({
   //Google验证码开关
    googleCode : false,
    //登录图形验证码开关
    captchaLoginH5 : false,
    //注册图形验证码开关
    captchaRegisterH5 : false,
    // h5邮箱验证码
    // emailCodeFlag: false,
    // h5邮箱登录验证码
    emailCodeLoginFlag: false,
        // h5邮箱注册验证码
    emailCodeRegisterFlag: false,
    //h5邀请码开关
    inviteCode : false,
    //手机号格式开关
    phoneValid : false,
    //资金密码开关
    walletPasswordValid : false,
    //短信邮箱开关
    smsOrEmailOtp : false
})
onMounted(() => {
  // nameInput.value?.focus()
  console.log('@inviteCode:', route.query.inviteCode)
  getcaptchaImage();
  ApiConfig({
    key: 'CODE_SETTING'
  }).then(res => {
    GETCODE_SETTING.value = res.data
  })
})

// 邮箱验证函数
const validateEmail = (username: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(username)
}
// const validateEmailCod = () => {

//   if(GETCODE_SETTING.value.captchaLoginH5){
//     if (!form.captcha) {
//       formErrors.captcha = true;
//       formErrors.email = true

//       ElMessage.error(t('请输入验证码'))


//       return false
//     }
//   }else{
//     if (!form.email) {
//       formErrors.email = true;
//       formErrors.captcha = true;

//       ElMessage.error(t('请输入验证码'))

//       return false
//     }
//   }
//   formErrors.captcha = false
//   formErrors.email = false
//   return true
// }
//发送验证码
const countdown = ref(0)
const newEmailCountdown = ref(0)
const handleResend = async () => {
  try {
    if (!form.username) {
      ElMessage.error(t('请输入邮箱地址'))
    return
  }
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success(t('验证码已发送'))
    startCountdown('current')
  } catch (error) {
    ElMessage.error(t('发送失败，请重试'))
  }
}
const startCountdown = async (type: 'current' | 'new') => {
  ApiSendEmail({email: form.username}).then(res => {
    ElMessage.success(res.msg || t('验证码已发送'))
    const target = type === 'current' ? countdown : newEmailCountdown
    target.value = 60
    const timer = setInterval(() => {
      target.value--
      if (target.value <= 0) clearInterval(timer)
    }, 1000)
  }).catch(() => {
    ElMessage.error(t('发送失败'))
  })
}
const handleRegister = async () => {
  try {
    // 表单验证
    // formErrors.name = !form.name
    formErrors.username = !form.username || !validateEmail(form.username)
    formErrors.password = !form.password || form.password.length < 6
    formErrors.confirmPassword = form.password !== form.confirmPassword

    if (Object.values(formErrors).some(error => error)) {
      if (!form.username) {
        ElMessage.error(t('请输入邮箱地址'))
      } else if (!validateEmail(form.username)) {
        ElMessage.error(t('请输入正确的邮箱格式'))
      } else {
        ElMessage.error(t('请填写所有必填项'))
      }
      return
    }

    isLoading.value = true
    ApiRegister({
      username: form.username,
      emailCode: form.emailCode,
      password: form.password,
      uuid: GETCODE_SETTING.value.emailCodeRegisterFlag ? '':form.uuid,
      captcha:form.captcha,
      inviteCode: form.inviteCode || ''
    }).then(() => {
      ElMessage.success(t('注册成功'))
      router.push({
        path: '/login'
      })
      getcaptchaImage();
    }).finally(() => {
      isLoading.value = false;
      getcaptchaImage();
    })
    // router.push({
    //   path: '/register/verify',
    //   query: { username: form.username }
    // })
  } catch (error) {
    console.error('注册失败:', error)
    isLoading.value = false;
    getcaptchaImage();
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
}

.logo-container {
  padding: 14px 0 10px;
  text-align: center;
}

.main-content {
  flex: 1;
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: 1500px;
  margin: 0 auto;
}

.login-container {
  width: 350px;
}

.a-box {
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;

  .a-box-inner {
    padding: 25px 27px;
  }
}

.a-spacing-small {
  font-size: 28px;
  line-height: 1.2;
  font-weight: 400;
  margin-bottom: 18px;
}

.a-form-field {
  margin-bottom: 26px;
}

.a-form-label {
  display: block;
  padding-left: 2px;
  padding-bottom: 2px;
  font-weight: 700;
  font-size: 14px;
  line-height: 19px;
}

.a-input-text {
  width: 100%;
  height: 31px;
  padding: 3px 7px;
  line-height: normal;
  border: 1px solid #a6a6a6;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(0,0,0,.07) inset;
  font-size: 13px;

  &:focus {
    border-color: #e77600;
    box-shadow: 0 0 3px 2px rgba(228,121,17,.5);
  }

  &.a-form-error {
    border-color: #d00;
    box-shadow: 0 0 0 3px rgba(221,0,0,.1) inset;
  }

  &::placeholder {
    color: #767676;
  }
}

.a-form-alert {
  margin-top: 4px;
  font-size: 12px;
  line-height: 15px;
  color: #2b2b2b;
  display: flex;
  align-items: center;
  gap: 6px;

  i {
    font-size: 14px;
    color: #1296AB;
  }
}

.a-button-primary {
  width: 100%;
  height: 31px;
  font-size: 13px;
  background: #f4d078;
  background: linear-gradient(to bottom, #f7dfa5, #f0c14b);
  border: 1px solid;
  border-color: #a88734 #9c7e31 #846a29;
  border-radius: 3px;
  cursor: pointer;

  &:hover {
    background: linear-gradient(to bottom, #f5d78e, #eeb933);
  }

  &:disabled {
    background: #f9f9f9;
    border-color: #e7e7e7;
    cursor: not-allowed;
  }
}

.a-link-normal {
  color: #0066c0;
  text-decoration: none;

  &:hover {
    color: #c45500;
    text-decoration: underline;
  }
}

.a-divider-inner {
  height: 1px;
  background-color: #ddd;
  margin: 14px 0;
}

.sign-in-link {
  display: flex;
  gap: 4px;
  align-items: center;
  margin-bottom: 14px;
}

.business-section {
  display: flex;
  gap: 4px;
  align-items: center;
}

.a-size-mini {
  font-size: 12px;
  line-height: 1.5;
}

.a-spacing-top-small {
  margin-top: 10px;
}

.nav-logo-link {
  display: inline-flex;
  justify-content: center;
  text-decoration: none;
  padding: 0;
  height: 31px;
}

.amazon-logo {
  width: 103px;
  height: 31px;
  object-fit: contain;
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    width: 90%;
    max-width: 400px;
  }
}

.a-link-disabled {
  color: #565959;  // 使用亚马逊的禁用文本颜色
  text-decoration: none;
  cursor: default;  // 使用默认光标

  &:hover {
    color: #565959;  // 悬停时保持相同颜色
    text-decoration: none;  // 不显示下划线
  }
}
</style>
